package com.alsyun.common.validation.impl;

import com.alsyun.common.validation.Mobile;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * ©️ByteTube 2022-2024
 *
 * @author mark
 * @CreateTime: 2024-10-23
 * @Description:电话校验支持手机号和电话同时校验
 **/

public class MobileValidator implements ConstraintValidator<Mobile, String> {

    private static final Pattern PHONE =
            Pattern
                    .compile("^0?(13[0-9]|14[0-9]|15[0-9]|16[0-9]|17[0-9]|18[0-9]|19[0-9])[0-9]{8}$");
    private static final Pattern AREA_MOBILE =
            Pattern
                    .compile("0\\d{2,3}[-]?\\d{7,8}|0\\d{2,3}\\s?\\d{7,8}|13[0-9]\\d{8}|15[1089]\\d{8}");
    private static final Pattern MOBILE =
            Pattern
                    .compile("^[1-9]{1}[0-9]{5,8}$");

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if (value == null) {
            return false;
        }
        Matcher matcher;
        int length = value.length();
        if (length == 11) {
            matcher = PHONE.matcher(value);
        } else if (length > 9) {
            matcher = AREA_MOBILE.matcher(value);
        } else if (length > 0) { // 确保长度大于0
            matcher = MOBILE.matcher(value);
        } else {
            return false; // 长度为0或负数，直接返回false
        }

        return matcher.matches();
    }

    @Override
    public void initialize(Mobile constraintAnnotation) {

    }
}